package com.cnstrong.webview2

import android.net.Uri
import android.util.Log
import android.view.View
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import java.util.*

class X5WebViewClient(private val x5WebView: X5WebView, private val loadingView: View) :
    WebViewClient() {

    companion object {
        private const val TAG = "X5WebViewClient"
    }

    private val TSL_SAFER: MutableList<String> = ArrayList()

    init {
        TSL_SAFER.add("webapp.leke.cn")
    }

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        try {
            if (BuildConfig.DEBUG){
                Log.e(TAG, "callback==${url}")
            }
            val parse = Uri.parse(url)
            val scheme = parse.scheme
            if (Constant.SCHEME == scheme) {
                val host = parse.host
                if (host == null || host.isEmpty()) {
                    return true
                }
                val param = parse.getQueryParameter(Constant.GET_PARAM)
                val callback = parse.getQueryParameter(Constant.GET_CALLBACK)
                val handler = x5WebView.findHtmlDataReceiver(host)
                handler?.onReceivedData(param, callback)
                return true
            }
        } catch (e: Exception) {
            Log.e(TAG, "exception==" + e.message)
        }
        x5WebView.loadUrl(url)
        return true
    }


    override fun onPageFinished(webView: WebView?, url: String?) {
        super.onPageFinished(webView, url)
        loadingView.visibility = View.GONE
        x5WebView.visibility = View.VISIBLE
    }

    override fun onReceivedSslError(
        webView: WebView,
        sslErrorHandler: SslErrorHandler,
        sslError: SslError?
    ) {
        try {
//            val url = webView.url
//            val uri = Uri.parse(url)
//            val domainName = uri.host
//            Log.e(TAG, "domainName == $domainName")
//            TSL_SAFER.forEach {
//                if (it.equals(domainName,true)){
//                    sslErrorHandler.proceed()
//                }
//            }
            sslErrorHandler.proceed() // 忽略证书错误，继续加载；
        } catch (e: java.lang.Exception) {
            Log.e(TAG, "ssl error")
        }
        //如果通过白名单验证，那么就通过安全校验;
        super.onReceivedSslError(webView, sslErrorHandler, sslError)
    }

    override fun onReceivedError(webView: WebView?, i: Int, s: String?, s1: String?) {
        super.onReceivedError(webView, i, s, s1)
        loadingView.visibility = View.GONE
        x5WebView.visibility = View.VISIBLE
        x5WebView.loadUrl(Constant.NO_NETWORK_ERROR_URL)
    }

}